package com.yindian.cos.easy.security.authentication.login.social.weibo;

import com.alibaba.fastjson.JSONObject;
import com.yindian.cos.easy.security.authentication.login.social.core.AbstractUserInfoFactory;
import com.yindian.cos.easy.security.authentication.login.social.core.AccessToken;
import com.yindian.cos.easy.security.constant.ProviderName;
import com.yindian.cos.easy.security.exception.UserInfoException;
import com.yindian.cos.easy.security.properties.EasySecurityProperties;
import com.yindian.cos.easy.security.properties.WeiBoProperties;
import org.springframework.web.client.RestTemplate;

/**
 * 微博获取UserInfo默认实现
 *
 * @author zhangchuanhao
 * @create 2018/11/20
 */
public class WeiBoUserInfoFactory extends AbstractUserInfoFactory<WeiBoUserInfo> {

    private EasySecurityProperties easySecurityProperties;

    private RestTemplate restTemplate;

    public WeiBoUserInfoFactory(EasySecurityProperties easySecurityProperties, RestTemplate restTemplate) {
        this.easySecurityProperties = easySecurityProperties;
        this.restTemplate = restTemplate;
    }

    @Override
    public WeiBoUserInfo getUserInfo(AccessToken accessToken) {
        try {
            WeiBoAccessToken weiBoAccessToken = (WeiBoAccessToken) accessToken.getOthers().get("weiBoAccessToken");
            WeiBoProperties weiBoProperties = easySecurityProperties.getWeibo();
            String url = weiBoProperties.getUserInfoUrl();
            url += "?access_token=" + accessToken.getAccessToken();
            url += "&uid=" + weiBoAccessToken.getUid();
            String result = restTemplate.getForObject(url, String.class);
            WeiBoUserInfo userInfo = JSONObject.parseObject(result, WeiBoUserInfo.class);
            return userInfo;
        } catch (Exception ex) {
            throw new UserInfoException(ProviderName.WEIBO + "登录获取用户信息失败", ex.getCause());
        }
    }
}
